#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <qtextcodec.h>
#include <qmessagebox.h>
#include <qfile.h>
#include <qprocess.h>
#include <qtimer.h>
MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    InitUI();
    //    ui->tableWidget->setSelectionBehavior(QAbstractItemView::SelectRows);  //整行选中的方式
    //    Selecting single items
    ui->tableWidget->setSelectionBehavior(QAbstractItemView::SelectItems); //选中单个单元格
    //    ui->tableWidget->setEditTriggers(QAbstractItemView::NoEditTriggers);   //禁止修改
    ui->tableWidget->setColumnCount(21);
    //    ui->tableWidget->setRowCount(1);
    ui->tableWidget->setColumnWidth(0,240);

    this->setWindowTitle("屁股大师   股市有风险投资需谨慎  软件仅供用于学习参考使用");
    this->setWindowIcon(QIcon("bird.ico"));
    LogStr("本软件仅供用于股票学习、参考，切勿用于其他用途，否则后果自负！");
    //    载入自选数据
    QFile fs("stock.txt");
    if(!fs.open(QIODevice::ReadOnly|QIODevice::Text))
    {
        LogStr("文件不存在");
    }

    QString tmpStr =QString(fs.readAll());
    CustStock = tmpStr.split("|");

    //    th.create(on_queryBig_5_clicked)
    on_queryBig_5_clicked();
    qtimer = new QTimer(this);
    qtimer->setInterval(1000);
    connect(qtimer,SIGNAL(timeout()),this,SLOT(UpDateTime()));
    qtimer->start();
    //    刷新自选函数

    //    共20列
}

MainWindow::~MainWindow()
{
    delete ui;
}


void MainWindow::on_queryStock_clicked()
{
    //    获取股票代码 开始获取数据
    QString StockCode = ui->lineEdit->text();
    qDebug()<<StockCode;

    GetDataByStockCode(StockCode);

}

QByteArray MainWindow::Http_Get(QString url)
{
    //    https访问 配置
    QSslConfiguration conf;
    conf.setPeerVerifyMode(QSslSocket::VerifyNone);
    conf.setProtocol(QSsl::AnyProtocol);


    QNetworkRequest request;
    request.setUrl(QUrl(url));
    request.setSslConfiguration(conf);
    QNetworkAccessManager*  netManager = new QNetworkAccessManager();
    QNetworkReply* reply = netManager->get(request);

    //    实现同步调用 阻塞
    QEventLoop eventLoop;
    connect(reply,&QNetworkReply::finished,&eventLoop,&QEventLoop::quit);
    eventLoop.exec(QEventLoop::ExcludeUserInputEvents);

    int statusCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
    QVariant redirectAttr = reply->attribute(QNetworkRequest::RedirectionTargetAttribute);
    if (reply->error()
            || 300 == statusCode //状态码300 Multiple Choices，既不是错误也不算重定向，应该是qt bug
            || !redirectAttr.isNull())
    {
        QString errString = reply->error() ? reply->errorString() : QString("发生重定向(%1)，不允许此情况").arg(statusCode);
    }

    QByteArray replyData = reply->readAll();
    qDebug()<<reply->rawHeader("Content-Encoding");
    reply->deleteLater();
    reply=nullptr;
    return  replyData;
}

void MainWindow::AddDataToTable(QStringList datalist,QString StockCode)
{

    int table_index = -1;
    if(datalist.isEmpty())
    {
        this->setWindowTitle("获取数据出错！ 请尝试重新获取");
        return;
    }
    for (int index=0;index<ui->tableWidget->rowCount();index++) {
        QString tmpString = ui->tableWidget->item(index,20)->text();
        //        判断表格中是否存在该股票 若存在 则更新该股票
        if(tmpString == StockCode)
        {
            table_index = index;
            break;
        }
    }
    //    如果table_index=-1表示表格中不存在这支股票
    if(table_index == -1)
    {
        table_index = ui->tableWidget->rowCount();
        ui->tableWidget->insertRow(table_index);
    }
    //
    //    int table_index = ui->tableWidget->rowCount()-2;


    qDebug()<<ui->tableWidget->rowCount();
    //设置名称以及第一列的颜色
    ui->tableWidget->setItem(table_index,0,new QTableWidgetItem(datalist.at(0)+"|"+datalist.at(30)+" "+datalist.at(31)));
    ui->tableWidget->item(table_index,0)->setForeground(QBrush(QColor("#FFF30D")) );
    ui->tableWidget->item(table_index,0)->setTextAlignment(Qt::AlignHCenter|Qt::AlignVCenter);

    for (int i=1;i<=9;i++) {
        ui->tableWidget->setItem(table_index,i,new QTableWidgetItem(datalist.at(i)));
        if(i == 3){
            float yesdayPrice = ui->tableWidget->item(table_index,2)->text().toFloat();
            float todayPrice = ui->tableWidget->item(table_index,3)->text().toFloat();
            if(yesdayPrice > todayPrice){
                float downf = (yesdayPrice-todayPrice)/yesdayPrice  * 100;
                //                涨跌百分比 此为跌幅
                QString tmpstr =datalist.at(i)+ " | -"+ QString::number(downf,'f',2)+"%";

                ui->tableWidget->setItem(table_index,i,new QTableWidgetItem(QIcon("down.png"),tmpstr));
                ui->tableWidget->item(table_index,i)->setForeground(QBrush(QColor("green")) );
            }
            else{
                float downf = (todayPrice-yesdayPrice)/yesdayPrice  * 100;
                //                涨跌百分比 此为涨幅
                QString tmpstr =datalist.at(i)+ " | "+ QString::number(downf,'f',2)+"%";

                ui->tableWidget->setItem(table_index,i,new QTableWidgetItem(QIcon("up.png"),tmpstr));
                ui->tableWidget->item(table_index,i)->setForeground(QColor("red"));
            }
        }
        if(i == 4){
            float yesdayPrice = ui->tableWidget->item(table_index,2)->text().toFloat();
            float todayPrice = ui->tableWidget->item(table_index,4)->text().toFloat();
            if(yesdayPrice > todayPrice){
                ui->tableWidget->setItem(table_index,i,new QTableWidgetItem(datalist.at(i)));
                ui->tableWidget->item(table_index,i)->setForeground(QBrush(QColor("green")) );
            }
            else{

                ui->tableWidget->setItem(table_index,i,new QTableWidgetItem(datalist.at(i)));
                ui->tableWidget->item(table_index,i)->setForeground(QColor("red"));
            }
        }

        if(i == 5){
            float yesdayPrice = ui->tableWidget->item(table_index,2)->text().toFloat();
            float todayPrice = ui->tableWidget->item(table_index,5)->text().toFloat();
            if(yesdayPrice > todayPrice){
                ui->tableWidget->setItem(table_index,i,new QTableWidgetItem(datalist.at(i)));
                ui->tableWidget->item(table_index,i)->setForeground(QBrush(QColor("green")) );
            }
            else{

                ui->tableWidget->setItem(table_index,i,new QTableWidgetItem(datalist.at(i)));
                ui->tableWidget->item(table_index,i)->setForeground(QColor("red"));
            }


        }
        ui->tableWidget->item(table_index,i)->setTextAlignment(Qt::AlignHCenter|Qt::AlignVCenter);

    }
    //    买一-买五报价 卖一到卖五及报价
    for(int j=0;j<10;j++){
        ui->tableWidget->setItem(table_index,10+j,new QTableWidgetItem(datalist.at(10+j*2)+"&"+datalist.at(10+j*2+1)));
        ui->tableWidget->item(table_index,10+j)->setTextAlignment(Qt::AlignHCenter|Qt::AlignVCenter);

    }


    //    显示股票代码
    ui->tableWidget->setItem(table_index,20,new QTableWidgetItem(StockCode));
    ui->tableWidget->item(table_index,20)->setTextAlignment(Qt::AlignHCenter|Qt::AlignVCenter);
    ui->tableWidget->item(table_index,20)->setForeground(QBrush(QColor("red")) );


}

void MainWindow::LogStr(QString qstr)
{
    qDebug()<<qstr;
}

void MainWindow::InitUI()
{
    ui->label_2->setOpenExternalLinks(true);

    ui->label_2->setText("< a style='color:#FFFFFF' href=\"http://www.cet.com.cn/\">中国经济报 http://www.cet.com.cn/");

    ui->label_3->setOpenExternalLinks(true);
    ui->label_3->setText("< a style='color:#FFFFFF' href=\"http://paper.people.com.cn/\">人民日报 http://paper.people.com.cn/");

    ui->label_4->setOpenExternalLinks(true);
    ui->label_4->setText("< a style='color:#FFFFFF' href=\"https://www.caijing.com.cn/\">今日财经 https://www.caijing.com.cn/");

    ui->label_5->setOpenExternalLinks(true);
    ui->label_5->setText("< a style='color:#FFFFFF' href=\"http://www.chinapolicy.net/\">中国政策网 http://www.chinapolicy.net/");

    ui->label_6->setOpenExternalLinks(true);
    ui->label_6->setText("< a style='color:#FFFFFF' href=\"http://vip.stock.finance.sina.com.cn/mkt/\">更多股市行情,点我进入新浪财经+");
    QFile f(":qdarkstyle/dark/style.qss");

    if (!f.exists())   {
        LogStr("Unable to set stylesheet, file not found\n");
    }
    else   {
        f.open(QFile::ReadOnly | QFile::Text);
        QTextStream ts(&f);

        qApp->setStyleSheet(ts.readAll());
    }
}

void MainWindow::GetDataByStockCode(QString code)
{
    QByteArray data = Http_Get("https://hq.sinajs.cn/list=sh"+code);
    LogStr("获取数据");
    //    编码转换 GBK编码转为UTF 再转换到QT的字符编码
    QTextCodec *gbk = QTextCodec::codecForName("GBK");
    QString g2u = gbk->toUnicode(data);
    data = g2u.toUtf8();
    QString StrData = QString::fromUtf8(data);

    //文本处理 获取中间文本
    int firstIndex = StrData.indexOf('"');
    int lastIndex = StrData.indexOf('"',firstIndex+1);
    StrData = StrData.mid(firstIndex+1,lastIndex-firstIndex-1);
    qDebug()<<StrData;
    if(StrData.isNull() | StrData.isEmpty())
    {
        QMessageBox::information(this,"错误","获取信息失败 请检查股票代码");
        return;
    }
    QStringList dataList = StrData.split(',');
    qDebug()<<dataList;
    AddDataToTable(dataList,code);
}

QString MainWindow::GetMidStr(QString src, QString headStr, QString backStr)
{
    int firstIndex = src.indexOf(headStr)+headStr.length()-1;
    int lastIndex = src.indexOf(backStr,firstIndex);
    QString  StrData = src.mid(firstIndex+1,lastIndex-firstIndex-1);
    return StrData;
}

void MainWindow::DelStockByCode(QString StockCode)
{
    int rowCount = ui->tableWidget->rowCount();
    for (int i=0;i<rowCount;i++) {
        QString Str = ui->tableWidget->item(i,20)->text();
        if( Str == StockCode)
        {
            ui->tableWidget->removeRow(i);

        }
    }
}

void MainWindow::autoUpdate()
{
    qDebug()<<"正在获取数据";
    int count = ui->tableWidget->rowCount();
    QStringList tmpList,currentTable;
    for (int i=0;i<count;i++) {
        QString currentCode = ui->tableWidget->item(i,20)->text();
        currentTable.append(currentCode);
        tmpList.append("sh"+ currentCode);
    }
    QString qstr = tmpList.join(",");
    QByteArray data = Http_Get("https://hq.sinajs.cn/list="+qstr);
    QTextCodec *gbk = QTextCodec::codecForName("GBK");
    QString g2u = gbk->toUnicode(data);
    data = g2u.toUtf8();
    QString NetSinaData = QString::fromUtf8(data);
    qDebug()<<NetSinaData;

    for (int j=0;j<count;j++) {
        QString headStr = currentTable.at(j);
        headStr.append('=');
        headStr.append('"');
        QString MidStr = GetMidStr(NetSinaData,headStr,QString('"'));
        QStringList tmpList = MidStr.split(",");
        if(tmpList.isEmpty() | tmpList.length()<10)
        {
            continue;
        }
        QString StockCode = currentTable.at(j);
        AddDataToTable(tmpList,StockCode);
    }
}

void MainWindow::UpDateTime()
{
    QTime curTime = QTime::currentTime();

    ui->lcdNumber->display(curTime.hour());
    ui->lcdNumber_2->display(curTime.minute());
    ui->lcdNumber_3->display(curTime.second());
    qDebug()<<"定时器正在运行！！！";
}

void MainWindow::on_pushButton_2_clicked()
{
    if(!CustStock.contains(ui->lineEdit->text()))
    {
        CustStock.append(ui->lineEdit->text());
        QFile fs("stock.txt");
        if(!fs.open(QIODevice::WriteOnly | QIODevice::Text)){
            QMessageBox::information(this,"error","打开文件失败");
        }
        QString tmpStr = CustStock.join("|");
        fs.write(tmpStr.toLatin1().data());
        fs.close();
        QMessageBox::information(this,"success","加入自选成功");
        return;
    }
    QMessageBox::information(this,"Error","该股票以及存在自选,请勿重复添加");

    //    加入自选股票
}

void MainWindow::on_queryBig_3_clicked()
{
    selfUpDlg = new Dialog(this);
    selfUpDlg->show();
    //    个股涨幅榜界面

}

void MainWindow::on_pushButton_clicked()
{

    QProcess process(0);
    process.start("notepad " + QApplication::applicationDirPath()+ "/fl.txt");
    process.waitForFinished(1000000);
    qDebug()<<"进程已经关闭";

}

void MainWindow::on_queryHis_clicked()
{
    //    删除自选

    if(CustStock.contains(ui->lineEdit->text()))
    {
        int index = CustStock.indexOf(ui->lineEdit->text());

        CustStock.removeAt(index);
        QFile fs("stock.txt");
        if(!fs.open(QIODevice::WriteOnly | QIODevice::Text)){
            QMessageBox::information(this,"error","打开文件失败");
        }
        QString tmpStr = CustStock.join("|");
        fs.write(tmpStr.toLatin1().data());
        fs.close();
        on_queryBig_5_clicked();
        QMessageBox::information(this,"success","删除成功");
        return;
    }
    QMessageBox::information(this,"Error","删除失败,该股票不存在自选中");
}

void MainWindow::on_tableWidget_itemClicked(QTableWidgetItem *item)
{
    int currentRow = item->row();
    qDebug()<<"单机的股票代码"<<ui->tableWidget->item(currentRow,20)->text();
    ui->lineEdit->setText(ui->tableWidget->item(currentRow,20)->text());
}
void GetStockSelf(){


}
void MainWindow::on_queryBig_5_clicked()
{
    //         MainWindow::GetDataByStockCode(MainWindow::CustStock.at(i));
    //    刷新自选
    QStringList tmpList;
    ui->plainTextEdit->setPlainText("");
    ui->plainTextEdit->appendPlainText("我的自选");
    for(int row = ui->tableWidget->rowCount() - 1;row >= 0; row--)
    {
        ui->tableWidget->removeRow(row);
    }
    for (int i=0;i<MainWindow::CustStock.length();i++) {
        ui->plainTextEdit->appendPlainText(CustStock.at(i));
        tmpList.append("sh"+ CustStock.at(i));
    }
    QString qstr = tmpList.join(",");
    qDebug()<<qstr;
    QByteArray data = Http_Get("https://hq.sinajs.cn/list="+qstr);
    QTextCodec *gbk = QTextCodec::codecForName("GBK");
    QString g2u = gbk->toUnicode(data);
    data = g2u.toUtf8();
    QString NetSinaData = QString::fromUtf8(data);
    qDebug()<<NetSinaData;

    for (int j=0;j<CustStock.length();j++) {
        QString headStr = CustStock.at(j);
        headStr.append('=');
        headStr.append('"');
        QString MidStr = GetMidStr(NetSinaData,headStr,QString('"'));
        QStringList tmpList = MidStr.split(",");
        if(tmpList.isEmpty() | tmpList.length()<10)
        {
            continue;
        }
        QString StockCode = CustStock.at(j);
        AddDataToTable(tmpList,StockCode);
    }


}

void MainWindow::on_queryBig_6_clicked()
{
    antoTimer = new QTimer(this);
    antoTimer->setInterval(10000);
    connect(antoTimer,SIGNAL(timeout()),this,SLOT(autoUpdate()));
    antoTimer->start();
    ui->queryBig_6->setText("正在获取最新信息");
    ui->queryBig_6->setDisabled(true);
}

void MainWindow::on_queryBig_7_clicked()
{
    ui->queryBig_6->setText("开始获取实时数据");
    antoTimer->stop();
    ui->queryBig_6->setDisabled(false);
}
